<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 你不应该一上来就知道用递归,你应该先写代码写的时候发现有重复 
        // 不确定有几层 只能用递归
        // parent id 父级id 
        var depts = [
            { id: 1, pid: "", name: "aaa" },
            { id: 2, pid: 1, name: "bbb" },
            { id: 3, pid: 1, name: "ccc" },
            { id: 5, pid: "", name: "eee" },
            { id: 6, pid: 2, name: "fff" },
        ];

        function fn (pid) {
            const arr = []
            depts.forEach((item) => {
                if (item.pid === pid) {
                    arr.push(item)
                    const arr1 = fn(item.id)//把自己作为父级 那么自己的id就是pid 
                    if (arr1.length > 0) {
                        item.children = arr1
                    }
                }
            })
            return arr
        }

        console.log(fn(''));
    </script>
</body>

</html>